
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
  <meta name="description" content="xms">
  <meta name="author" content="Xms">
  <link rel="icon" href="/content/favicon.ico">

  <title>组织 - 安全 - 安全角色 - 角色授权</title>

  <!-- Bootstrap core CSS -->
  <link href="/content/css/bootstrap3.3.5/bootstrap.min.css" rel="stylesheet">

  <!-- Custom styles for this template -->
  <link href="/content/css/font-awesome.min.css" rel="stylesheet">
  <link href="/content/css/common.css" rel="stylesheet">
  <link href="/content/js/jquery-toast/jquery.toast.min.css" rel="stylesheet">
  <link id="themeLink" href="/content/css/theme/default.css" rel="stylesheet" />
  <!-- Bootstrap core JavaScript ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <script src="/content/js/jquery.min.js"></script>
  <script src="/content/js/bootstrap.min.js"></script>
  <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
  <script src="/content/js/ie10-viewport-bug-workaround.js"></script>
  <script src="/content/js/jquery.bootstrap.min.js"></script>
  <script src="/content/js/json2.js"></script>
  <script src="/content/js/xms.utility.js"></script>
  <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.core.js"></script>
  <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.widget.js"></script>
  <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.mouse.js"></script>
  <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.draggable.js"></script>
  <script src="/content/js/jquery-toast/jquery.toast.min.js"></script>
  <script src="/content/js/xms.jquery.js"></script>
  <script src="/content/js/xms.web.js"></script>
  <script src="/content/js/commonlabels.js"></script>
  <script src="/content/js/common/pagecontext.js"></script>
  <script src="/api/user/usercontext"></script>
  <script>
  jQuery(function () {
    Xms.Web.Loading();
    if (typeof parent !== 'undefined') {
      if (parent != window) {//判断当前页面是否为子页面
        $('body').addClass('xms-subpage');
      }
    }
  });
  function changeTheme(body,themename) {
    $("#themeLink").attr('href', '/content/css/theme/' + themename+'.css');
  }
</script>
  <link href="/content/css/jqtree.css" rel="stylesheet">
  <style>
    body {
      padding-top: 0;
    }
  </style>
</head>

<body data-spy="scroll" data-target="#myScrollspy">
<div class="container-fluid" id="body">
  <div class="row">
    <div class="shadeBox" style="background-color:#000000; opacity:0.5;width:100%;position:absolute;z-index:10;display:none;"></div>
    <div class="col-md-12" id="main" style="margin-bottom:80px;">
      <div><br class="breadcrumb" /></div>
      <div id="content"></div>
      <div class="page-render-wrap">
        <!--main-->

        <div class="container-fluid">
          <div class="row" style="padding:5px 0px;">
            <div class="col-sm-11 btn-group" id="owners">
              <button type="button" class="btn btn-sm btn-default">类型：</button>
            </div>
          </div>
          <div class="row">
            <div class="col-sm-4">
              <div class="panel panel-default">
                <div class="panel-heading">
                  <h3 class="panel-title">
                    <a data-toggle="collapse"
                       href="#collapseOne">
                      <strong id="rolename" class="text-primary"></strong> - <strong id="resourcelocalizedname"></strong>
                    </a>
                  </h3>
                </div>
                <div id="collapseOne" class="panel-collapse collapse in">
                  <div class="panel-body">
                    <form id="editform" class="form-horizontal" data-jsonajax="true" data-formdata="false" data-istip="true" action="/xms/api/security/roleobjectaccess/save" method="post">
                      <input data-val="true" id="RoleId" name="roleid" type="hidden" />
                      <input id="ResourceName" name="resourcename" type="hidden" />
                      <div class="btn-group col-sm-offset-3">
                        <button class="btn btn-default" type="button" data-toggle="button" id="toggleChecked" data-state="1">
                          <span class="glyphicon glyphicon-check"></span> 全选 / <span class="glyphicon glyphicon-unchecked"></span> 取消
                        </button>
                        <button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-saved"></span> 保存</button>
                      </div>
                      <hr />
                      <div id="tree1" data-url="/xms/api/security/privilege/tree" style="min-height:400px;max-height:400px; overflow:auto;">
                      </div>
                    </form>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-sm-8">
              <table class="table table-hover table-bordered  table-striped table-condensed">
                <thead>
                <tr>
                  <th>角色名称</th>
                  <th width="30%">操作</th>
                </tr>
                </thead>
                <tbody data-bind="foreach: lines">
                <tr>
                  <td>
                    <a href="#" data-bind="click: $root.click"><span data-bind="text: name"></span></a>
                  </td>
                  <td>
                    <a class="btn btn-info btn-xs" data-bind="click: $root.click"><span class="glyphicon glyphicon-lock"></span> 权限</a>
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>

      </div>
      <nav class="navbar navbar-default navbar-fixed-bottom hide" role="navigation" id="body-footer">
        <div class="container">
          <div class="navbar-form navbar-right" id="body-footer-content">
          </div>
        </div>
      </nav>
    </div>
  </div>
</div>

<script src="/content/js/xms.utility.js"></script>
<script src="/content/js/jquery.form.js"></script>
<script src="/content/js/jquery-validate/jquery.validate.min.js"></script>
<script src="/content/js/xms.web.js"></script>
<script src="/content/js/xms.jquery.js"></script>
<script src="/content/js/tree.jquery.js"></script>
<script src="/content/js/knockout-2.2.0.js"></script>
<script>
  var $tree = $('#tree1'), $editform = $("#editform");
  var model = $.urlParamObj(location.href);
  $(function () {
    $('#RoleId').val(model.roleid);
    $('#ResourceName').val(model.resourcename);
    Xms.Web.Loading();
    Xms.Web.Form($editform, function (response) {
      Xms.Web.Alert(response.IsSuccess, response.Content || response.ErroeMessage);
    });
    //表单验证
    //Xms.Web.Form($form);
    $("#toggleChecked").click(function () {
      var state = $(this).attr("data-state");
      if (state == 1) {
        $tree.find("input[type=checkbox]").prop("checked", true);
        $(this).attr("data-state", 0).removeClass("active");
      } else {
        $tree.find("input[type=checkbox]").prop("checked", false);
        $(this).attr("data-state", 1).addClass("active");
      }
    });

    Xms.Web.GetJson(ORG_SERVERURL + "/api/security/role/list?statecode=true&getall=true", null, function (data) {
      if (!data || !data.Content || data.Content.length == 0) return;
      var data = data.Content;
      var Items = function () {
        var self = this;
        data = $.grep(data, function (n, i) {
          return n.name.toLowerCase() != 'administrator';
        });
        self.lines = ko.observableArray(data);

        self.click = function (item) {
          $tree.tree('reload');
          $('#rolename').text(item.name);
          loadRolePrivileges(item.roleid);
        }
      }
      ko.applyBindings(new Items());
      currentRole = $.grep(data, function (n, i) {
        return n.roleid == model.roleid;
      });
      if(currentRole) $('#rolename').text(currentRole[0].name);
    });
    Xms.Web.GetJson(ORG_SERVERURL + "/api/security/resourceowners", null, function (data) {
      if (!data.IsSuccess) return;
      var items = data.Content;
      var resourceName = $('#ResourceName').val().toLowerCase();
      var $container = $('#owners');
      $(items).each(function (i, n) {
        if(!n.statecode) return true;
        var url = (n.uiendpoint || '/security/editrolepermission') + '?roleid=' + $("#RoleId").val() + '&resourcename='+ n.modulename;
        $container.append($('<button type="button" class="btn btn-sm '+(resourceName == n.modulename.toLowerCase() ? 'btn-info' : 'btn-default')+'" data-url="' + url + '">' + (n.modulelocalizedname || n.modulename) + '</button>'));
      });
      $container.find('button').on('click', null, function () {
        Xms.Web.Redirect($(this).attr('data-url'));
      });
      currentRes = $.grep(items, function (n, i) {
        return n.modulename.toLowerCase() == model.resourcename.toLowerCase();
      });
      if(currentRes) {
        $('#resourcelocalizedname').text(currentRes[0].modulelocalizedname);
        if(currentRes[0].resourceendpoint)
          initTree(ORG_SERVERURL + currentRes[0].resourceendpoint + '?authorizationenabled=true');
      }
    });
  });

  function initTree(url){
    $tree.attr('data-url', url);
    var node_index = 0;
    $tree.tree({
      autoOpen: false
      , onCreateLi: function (node, $li) {

        if (node.id && node.id.indexOf('parentid_') == -1) {
          $li.find('.jqtree-title').before('<input type="checkbox" name="items['+node_index+'].objectid" data-name="objectid" onclick="setState(this)" value="' + node.id + '" />&nbsp;&nbsp;');
          node_index++;
        } else {
          $li.find('.jqtree-title').before('<input type="checkbox" name="parentid" onclick="setState(this)" value="' + node.id + '" />&nbsp;&nbsp;');
        }
        //if (node.id != '' && node.id > 0) {
        //    $tree.tree('openNode', node);
        //}
      }
      , selectable: false,
      onCanSelectNode: function (node) {
        $tree.tree('openNode', node);
        return true;
      },
      dataFilter: function (data) {
        if (!data || !data.Content) {
          $tree.html('<div class="col-sm-12 text-center"><h3 class="alert-warning">没有可授权的数据</h3></div>');
          $('#editform').find('button').attr('disabled', true);
          return false;
        }
        var roleid = $("#RoleId").val();
        var ResourceName = $("#ResourceName").val();
        if (roleid != '') {
          loadRolePrivileges(roleid, ResourceName);
        }
        console.log(data);
        data = data.Content;
        if(typeof data != 'object')
          data = JSON.parse(data);
        handlerDatas(data);
        return data;
      }
    });
    function handlerDatas(datas) {

      $.each(datas, function (i, n) {
        if (!n.id) {
          n.id = 'parentid_' + Xms.Utility.Guid.NewGuid().ToString()
        }
        if (n.children && n.children.length > 0) {
          handlerDatas(n.children);
        }

      });
    }
  }

  function loadRolePrivileges(roleid) {
    $("#RoleId").val(roleid);
    Xms.Web.GetJson(ORG_SERVERURL + "/api/security/roleobjectaccess/list?roleid=" + roleid + "&resourcename=" + model.resourcename, null, function (data) {
      if (!data.IsSuccess) return;
      var result = data.content;
      console.info(result);

      if (result.length > 0) {
        $(result).each(function (i, n) {
          if (!n.id) {
            var treeid = Xms.Utility.Guid.EmptyGuid.ToString()
            n.id = treeid;
            n.isparent = true;
          }
          setLoadedChildrenSelected(n.objectid);
        });
      }
      else {
        var node = $tree.tree('getNodeById', Xms.Utility.Guid.EmptyGuid.ToString());
        if (node) {
          $tree.tree('openNode', node);
        }
      }
    });
  }
  function setChildrenSelected(nodeid) {
    var node = $tree.tree('getNodeById', nodeid);
    if (!node) return;
    $(node.element).find("input[type=checkbox][value=" + nodeid + "]").prop("checked", true);
    if (node) {
      $tree.tree('openNode', node);
    }
    for (var i = 0; i < node.children.length; i++) {
      var child = node.children[i];
      if (child.children.length > 0) {
        setChildrenSelected(child.id);
      }

      var childnode = $tree.tree('getNodeById', child.id);
      $(childnode.element).find("input[type=checkbox][value=" + child.id + "]").prop("checked", true);
      if (childnode) {
        $tree.tree('openNode', childnode);
      }

    }
  }
  function setLoadedChildrenSelected(nodeid) {
    var node = $tree.tree('getNodeById', nodeid);
    if (!node) return;
    $(node.element).find("input[type=checkbox][value=" + nodeid + "]").prop("checked", true);
    if (node) {
      $tree.tree('openNode', node);
    }
    if (node.children.length == 0) {
      var par_ele = $(node.element).parent().siblings(".jqtree-element");
      if (par_ele.length > 0) {
        var paridDom = par_ele.find("input[data-name='objectid']"), parid = paridDom.val();
        if (!paridDom.prop("checked")) {
          var parid_treeid = $tree.tree('getNodeById', parid)
          if (parid_treeid) {
            $tree.tree('openNode', parid_treeid);
          }
        }
      }
    }
  }

  function setState(t) {

    var flag = $(t).prop("checked");
    var nodeid = $(t).val();
    if (flag) {
      setChildrenSelected(nodeid);
    }
    else {
      var node = $tree.tree('getNodeById', nodeid);
      if (node.children.length > 0) {
        $(node.element).find("input[type=checkbox]").prop("checked", false);
      }
    }
  }
</script>

</body>
</html>